package com.groupbuying.customer.service.impl;

import com.groupbuying.customer.constants.ModileCodeTypeConstants;
import com.groupbuying.customer.constants.RedisConstants;
import com.groupbuying.customer.service.CustomerService;
import com.groupbuying.customer.service.CustomerUshopService;
import com.groupbuying.customer.service.ModileCodeService;
import com.groupbuying.customer.service.SmsService;
import com.groupbuying.customer.utils.RedisUtils;
import com.groupbuying.customer.utils.ReturnUtils;
import com.groupbuying.customer.utils.apiresult.ApiResult;
import com.groupbuying.customer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @anthor wenguoqiang
 * @date: 2019/01/15 17:41
 * @company 蒙泰互联网公司
 * @des
 **/
@Service
public class ModileCodeServiceImpl implements ModileCodeService {

    private static Logger log = LoggerFactory.getLogger(ModileCodeServiceImpl.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerUshopService customerUshopService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SmsService smsService;

    @Override
    public Map getModileCodeServiceCode(Map<String, Object> mapParams) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        // 解析map参数
        Object tempParam = mapParams.get("mobile");
        Object typeParam = mapParams.get("type");
        String mobile = tempParam != null ? tempParam.toString() : null;
        Integer type = typeParam != null ? (Integer) typeParam : null;

        if (StringUtils.isEmpty(mobile) || type == null) {
            //参数为空检验
            returnMap = ReturnUtils.paramIsNull();
            return returnMap;
        }

        String code = "";
        for (int i = 0; i < 4; i++) {
            int x = (int) (Math.random() * 10);
            code += x;
        }

        //log.debug("手机验证码：" + code);
        // 调用短信发送接口发送验证码
        StringBuffer sb = new StringBuffer();
        // 发送短信返回结果
        boolean flag = true;
        if (ModileCodeTypeConstants.APP_REGISTER.getCode().equals(type)) {
            //注册用验证码
            //验证此手机号是否被注册过
            boolean isUshopMobileExist = customerUshopService.checkMobileExist(mobile);
            if (isUshopMobileExist) {
                return ApiResult.failure(ApiResultCode.MOBILEEXISTS, "");
            }

            flag =  smsService.sendCodeForRegister(mobile, code);

            if (!flag) {
                return ApiResult.failure(ApiResultCode.SENDCODEFAILURE, "");
            }

            // 将验证码放入redis中
            if (!redisUtils.setKey(RedisConstants.RDS_APP_REGISTER + mobile, code, 1800)) {
                return ApiResult.failure();
            }

            Map map = new HashMap();
            map.put("captcha", code);
            map.put("mobile", mobile);
            return ApiResult.success(ApiResultCode.SUCCESS_GETCODE, map);
        } else if (ModileCodeTypeConstants.FIND_PWD.getCode().equals(type)) {
            // 找回密码
            // 验证此手机号是否被注册过
            boolean isUshopMobileExist = customerUshopService.checkMobileExist(mobile);

            if (!isUshopMobileExist) {
                return ApiResult.failure(ApiResultCode.LOGINPHONENOTEXISTS, "");
            }

            flag = smsService.sendCodeForFindPwd(mobile, code);
            if (!flag) {
                return ApiResult.failure(ApiResultCode.SENDCODEFAILURE, "");
            }

            // 将验证码放入redis中
            if (!redisUtils.setKey(RedisConstants.RDS_FIND_PWD + mobile, code, 1800)) {
                return ApiResult.failure();
            }

            Map map = new HashMap();
            map.put("captcha", code);
            map.put("mobile", mobile);
            return ApiResult.success(ApiResultCode.SUCCESS_GETCODE, map);
        } else if (3 == type || 4 == type || 5 == type) {
            // 验证此手机号是否被注册过
            boolean isNameExist = customerService.checkCustomerNameExist(mobile);
            boolean isMobileExist = customerService.checkMobileExist(mobile);
            if (!isNameExist && !isMobileExist) {
                returnMap.put("return_code", ApiResultCode.LOGINNAMENOTEXISTS.code());
                returnMap.put("message", ApiResultCode.LOGINNAMENOTEXISTS.code());
                returnMap.put("success", false);
                returnMap.put("result", "");
                return returnMap;
            } else {
                sb.append("验证码：");
                sb.append(code);
                sb.append("，您正在进行短信验证。30分钟内有效，请勿泄露。");
                //flag = smsService.sendSmsMQ(mobile, sb.toString());
            }
        } else if (6 == type) {
            sb.append("验证码：");
            sb.append(code);
            sb.append("，您正在进行短信验证。30分钟内有效，请勿泄露。");
            // flag = smsService.sendSmsMQ(mobile, sb.toString());
        } else if (7 == type) {
           /*     // 通过手机号获取验证码 第三方那个绑定用 看看会员是否绑定过 不同类型的第三方账号 同时校验第三方时候绑定过
                CustomerDO customerModel = customerService.getCustomerModelByLoginNameOrMobileOrEmail(mobile);
                // 判断是否绑定过
                String unionid = (String) mapParams.get("unionid");
                String source = (String) mapParams.get("source");
                CustomerThirdMsgDO thirdMsgModel = customerThirdMsgService.getByUnionidAndType(unionid, source);
                if (customerModel == null) {
                    //查不到会员判断第三方是否绑定过
                    if (thirdMsgModel != null) {
                        // 绑定过
                        returnMap.put("return_code", ReturnCodeEnum.THIRDHASEXIT.getKey());
                        returnMap.put("message", ReturnCodeEnum.THIRDHASEXIT.getValue());
                        return returnMap;
                    }
                } else {
                    //查到会员 判断是否绑定过类似的账号
                    List<CustomerThirdMsgModel> list = customerThirdMsgService
                            .getCustomerThirdByCustomerUuid(customerModel.getUuid());
                    if (list != null && list.size() > 0) {
                        for (CustomerThirdMsgModel customerThirdMsgModel : list) {
                            if (customerThirdMsgModel.getThirdType().equals(source)) {
                                // 如果用户绑定过提示他
                                returnMap.put("return_code", ApiCodeStatus.THIRD_HAS_EXIT);
                                returnMap.put("message",
                                        ApiCodeStatus.getErrorCodeStatusMap().get(ApiCodeStatus.THIRD_HAS_EXIT));
                                return returnMap;
                            }
                        }
                    }
                }*/
            // 可以绑定发送验证码
            sb.append("验证码：");
            sb.append(code);
            sb.append("，您正在进行短信验证。30分钟内有效，请勿泄露。");
            //flag = smsService.sendSms_P2(mobile, sb.toString());
            //flag = smsService.sendSmsMQ(mobile, sb.toString());
            //O2O绑定
        } else if (8 == type) {
            // 可以绑定发送验证码
            sb.append("验证码：");
            sb.append(code);
            sb.append("，您正在进行短信验证。30分钟内有效，请勿泄露。");
            //flag = smsService.sendSms_P2(mobile, sb.toString());
            //flag = smsService.sendSmsMQ(mobile, sb.toString());
        } else if (9 == type) {
            // 可以绑定发送验证码
            sb.append("验证码：");
            sb.append(code);
            sb.append("，您正在进行短信验证。30分钟内有效，请勿泄露。");
            //flag = smsService.sendSms_P2(mobile, sb.toString());
            // flag = smsService.sendSmsMQ(mobile, sb.toString());
        }


        //发送完成
//        if (!flag) {
//            Subject smsSubject = SecurityUtils.getSubject();
//            Session session = smsSubject.getSession();
//            if (1 == type) {
//                session.setAttribute("appRegister_" + mobile, code);
//            } else if (2 == type) {
//                session.setAttribute("findPwd_" + mobile, code);
//            } else if (3 == type) {
//                session.setAttribute("changePayPwd_" + mobile, code);
//            } else if (4 == type) {
//                session.setAttribute("changePwd_" + mobile, code);
//            } else if (5 == type) {
//                session.setAttribute("original_" + mobile, code);
//            } else if (6 == type) {
//                session.setAttribute("new_" + mobile, code);
//
//                log.debug("getMobileCodeNoJson session ID : " + session.getId());
//                log.debug("getMobileCodeNoJson 向session中录入[new_" + mobile + "]校验码为 : " + code);
//            } else if (7 == type) {
//                session.setAttribute("new_" + mobile, code);
//            } else if (8 == type) {
//                session.setAttribute("O2O_" + mobile, code);
//            } else if (9 == type) {
//                session.setAttribute("CheckBank_" + mobile, code);
//            }
//
//            SessionContext.getInstance().addSession(session);
//
//
//            Map map = new HashMap();
//            map.put("captcha", code);
//            map.put("mobile", mobile);
//            map.put("sessionId", session.getId());
//
//
//            returnMap.put("resultCode", ApiResultCode.SUCCESS.code());
//            returnMap.put("resultMessage", ApiResultCode.SUCCESS.message());
//            returnMap.put("success", true);
//            returnMap.put("result", JsonUtils.objectToJson(map));
//        } else {
//            return ApiResult.failure();
//        }
        return ApiResult.failure();
    }

    @Override
    public Map checkModileCode(Map<String,Object> mapParams){
        Map<String, Object> returnMap = new HashMap<String, Object>();
        // 解析map参数
        Object tempParam = mapParams.get("mobile");
        String mobile = tempParam != null ? tempParam.toString() : null;
        tempParam = mapParams.get("captcha");
        String captcha = tempParam != null ? tempParam.toString() : null;
        Object typeParam = mapParams.get("type");
        Integer type = typeParam != null ? (Integer) typeParam : null;

        // 判断参数不为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(captcha)) {
            return ReturnUtils.paramIsNull();
        }

        if(ModileCodeTypeConstants.FIND_PWD.getCode().equals(type)){
            // 获取手机验证码
            String code = redisUtils.getValue(ModileCodeTypeConstants.FIND_PWD.getValue() + mobile).toString();
            if (StringUtils.isEmpty(code) || !code.equals(captcha)) {
                return ApiResult.success(ApiResultCode.VERIFICATIONCODEERROR, "");
            }
        }

        return ApiResult.success();
    }
}
